package com.heima.api.config;

import com.heima.model.admin.pojos.AdUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AdThreadLocalUtil;
import com.heima.utils.common.AppThreadLocalUtil;
import com.heima.utils.common.WmThreadLocalUtil;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

@Slf4j
public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLogLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {

                AdUser user = AdThreadLocalUtil.getUser();
                Integer userId = AppThreadLocalUtil.getUser();
                WmUser wmUser = WmThreadLocalUtil.getUser();
                String id = getUserId(userId, wmUser, user);
                if (id == null) {
                    return;
                }
                log.info("feign拦截器到的userId：{}", id);
                requestTemplate.header("userId", id);
            }

            private String getUserId(Integer userId, WmUser wmUser, AdUser user) {
                if (userId == null && wmUser == null && user == null) {
                    return null;
                }
                if (userId != null) {
                    return userId.toString();
                } else if (wmUser != null) {
                    return wmUser.getId().toString();
                } else {
                    return user.getId().toString();
                }
            }
        };
    }
}